﻿using System;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;


public sealed class DataTableGeneratorWindow : OdinEditorWindow
{
    [MenuItem("Tools/Generate App DataTables")]
    private static void GenerateDataTables2()
    {
        GetWindow<DataTableGeneratorWindow>();
    }

    [InfoBox("表格转换工具:*.txt => *.bytes + *.cs")]
    [InfoBox("生成代码路径 = 'Assets/Scripts/Game/DataTable'")]
    [SerializeField]
    [AssetList(Path = "RuntimeResources/DataTables/", CustomFilterMethod = "FilterDataTable")]
    [LabelText("待转换的表格")]
    private List<TextAsset> dataTableList;

    [Button(ButtonSizes.Large)]
    [LabelText("转换")]
    private void btn1()
    {
        if (dataTableList == null || dataTableList.Count == 0)
        {
            EditorUtility.DisplayDialog("Error", "you need select one or more files", "ok");
            return;
        }

        foreach (var datatable in dataTableList)
        {
            GenerateTable(datatable.name);
        }
        
        AssetDatabase.Refresh();
    }

    [Button(ButtonSizes.Large)]
    [LabelText("全部转换")]
    private void btn2()
    {
        var assets = System.IO.Directory.GetFiles($"{Application.dataPath}/RuntimeResources/DataTables");
        
        foreach (var asset in assets)
        {
            if (asset.EndsWith(".txt"))
            {
                GenerateTable(Path.GetFileNameWithoutExtension(asset));
            }
        }
        
        AssetDatabase.Refresh();
    }

    private bool FilterDataTable(TextAsset ta)
    {
        return AssetDatabase.GetAssetPath(ta).EndsWith(".txt");
    }

    private void GenerateTable(string tableName)
    {
        var dataTableProcessor =
            DataTableGenerator.CreateDataTableProcessor(DataTableFilePath, tableName);
        if (!DataTableGenerator.CheckRawData(dataTableProcessor, tableName))
        {
            Debug.LogError($"Check raw data failure. DataTableName='{tableName}'");
            EditorUtility.DisplayDialog("导表失败", "请检查数据结构类型", "确定");
        }

        DataTableGenerator.GenerateDataFile(dataTableProcessor, DataTableFilePath, tableName);
        DataTableGenerator.GenerateCodeFile(dataTableProcessor, DataTableCodePath, tableName);
    }

    /// <summary>
    /// 生成代码路径
    /// </summary>
    public const string DataTableCodePath = "Assets/Scripts/Game/DataTable";

    /// <summary>
    /// 生成文件路径
    /// </summary>
    public const string DataTableFilePath = "Assets/RuntimeResources/DataTables";
}



